<template>
  <view>
    <view class="order-list">
      <view
          v-for="(item, index) in orderList"
          :key="index"
          hover-class="none"
          class="order-item bg-white mt20"

      >
        <view class="order-header row-between">
          <view class="row">
            订单编号：{{ item.order_sn }}
          </view>
          <view class="order-status" :class="item.statusClass">
            <u-icon :name="item.statusIcon" size="28"></u-icon>
            <text class="status-text">{{ item.order_status_desc }}</text>
          </view>
        </view>
        <view class="order-con">
          <view class="order-info">
            <view class="info-row">
              <text class="label">服务名称：</text>
              <text class="value">{{ item.order_goods[0].goods_name || item.order_goods[0].name }}</text>
            </view>
            <view class="info-row">
              <text class="label">企业名称：</text>
              <text class="value">{{ item.company_name }}</text>
            </view>
            <view class="info-row">
              <text class="label">联系人：</text>
              <text class="value">{{ item.company_contact }}</text>
            </view>
            <view class="info-row">
              <text class="label">下单时间：</text>
              <text class="value">{{ item.create_time }}</text>
            </view>
          </view>
        </view>
        <view class="order-footer row-between">
          <price-format
              color="#222222"
              :showSubscript="false"
              :first-size="36"
              :second-size="36"
              :price="item.order_amount"
              :show-unit="true"
              unit="元"
              :unit-size="20"
              :weight="500"
          ></price-format>

          <view
              class="row"
              v-if="
            item.pickup_btn ||
            item.cancel_btn ||
            item.delivery_btn ||
            item.take_btn ||
            item.del_btn ||
            item.pay_btn ||
            item.comment_btn||
            item.negotiate_cancel_btn
          "
          >
            <view style="flex: 1">
              <view
                  class="primary sm row"
                  style="line-height: 26rpx"
                  v-if="getCancelTime(item.order_cancel_time) > 0"
              >
                <u-count-down
                    separator="zh"
                    :timestamp="getCancelTime(item.order_cancel_time)"
                    separator-color="#FF2C3C"
                    color="#FF2C3C"
                    :separator-size="26"
                    :font-size="26"
                    bg-color="transparent"
                    @end="reflesh"
                ></u-count-down
                >
              </view>
            </view>
            <view v-if="item.negotiate_cancel_btn">
              <button
                  size="sm"
                  class="btn plain br60 lighter"
                  hover-class="none"
                  @tap.stop="negotiateCancelOrder(item.id)"
              >
                协商取消
              </button>
            </view>
            <view v-if="item.cancel_btn">
              <button
                  size="sm"
                  class="plain br60 lighter"
                  hover-class="none"
                  @tap.stop="cancelOrder(item.id)"
              >
                取消订单
              </button>
            </view>
            <view v-if="item.del_btn">
              <button
                  size="sm"
                  class="btn plain br60 lighter"
                  hover-class="none"
                  @tap.stop="delOrder(item.id)"
              >
                删除订单
              </button>
            </view>
            <view v-if="item.pay_btn" class="ml20">
              <button
                  size="sm"
                  class="btn bg-primary br60 white"
                  @tap.stop="payNow(item.id)"
              >
                立即付款
              </button>
            </view>
            <view v-if="item.comment_btn" class="ml20">
              <button
                  size="sm"
                  hover-class="none"
                  class="btn plain br60 lighter"
                  @tap.stop="goToComment(item)"
              >
                去评价
              </button>
            </view>
            <view v-if="item.take_btn" class="ml20">
              <button
                  size="sm"
                  class="btn plain br60 lighter"
                  hover-class="none"
                  @tap.stop="comfirmOrder(item.id, item.pay_way)"
              >
                确认完成
              </button>
            </view>
            <view class="ml20">
              <button
                  size="sm"
                  class="btn br60 bg-primary white"
                  @tap.stop="goDetail(item.id)"
              >
                详情
              </button>
            </view>
          </view>
        </view>
      </view>
      <loading-footer :status="status" :slot-empty="true" @refresh="reload">
        <view slot="empty" class="column-center" style="padding-top: 200rpx">
          <image class="img-null" src="/static/images/goods_null.png"></image>
          <text class="lighter">暂无订单</text>
        </view>
      </loading-footer>
    </view>
    <order-dialog
        ref="orderDialog"
        :order-id="orderId"
        :type="type"
        @refresh="reflesh"
    ></order-dialog>
    <loading-view
        v-if="showLoading"
        background-color="transparent"
        :size="50"
    ></loading-view>
    <u-popup v-model="showNegotiatePopup" mode="center" border-radius="20" width="80%" closeable="true"   >
      <view class="negotiate-popup">
        <view class="popup-image">
          <image class="icon-alert" src="/static/images/icon-alert.png"></image>
        </view>
        <view class="popup-header">温馨提示</view>
        <view class="popup-content">服务中的订单无法取消，请联系平台客服处理</view>
        <view class="popup-footer row">
          <button class="popup-btn cancel-btn" @click="showNegotiatePopup = false">否</button>
          <button class="popup-btn confirm-btn" @click="goToCustomerService">是</button>
        </view>
      </view>
    </u-popup>
    <u-popup v-model="show" mode="center" border-radius="20" width="80%" closeable="true" @close="onClose" >
      <view class="comment-popup">
        <view class="popup-image">
          <image class="icon-pl" src="/static/images/icon-pl.png"></image>
        </view>
        <view class="popup-header">评价</view>
        <view class="comment-form">
          <view class="comment-item">
            <view class="comment-row">
              <view class="comment-label">服务效率</view>
              <u-rate v-model="formData.efficiency" :count="5" active-color="#ffb032"  inactive-color="#dddddd"
                      inactive-icon="star-fill"></u-rate>
            </view>
          </view>
          <view class="comment-item">
            <view class="comment-row">
              <view class="comment-label">服务技能</view>
              <u-rate v-model="formData.skill" :count="5" active-color="#ffb032" inactive-color="#dddddd"
                      inactive-icon="star-fill"></u-rate>
            </view>
          </view>
          <view class="comment-item">
            <view class="comment-row">
              <view class="comment-label">服务态度</view>
              <u-rate v-model="formData.attitude" :count="5" active-color="#ffb032" inactive-color="#dddddd"
                      inactive-icon="star-fill"></u-rate>
            </view>
          </view>
          <view class="comment-item">
            <view class="comment-label">评价内容</view>
            <textarea
                v-model="formData.content"
                placeholder="请输入您的评价内容"
                class="comment-textarea"
            ></textarea>
          </view>
        </view>
        <view class="popup-footer row">
          <button class="popup-btn cancel-btn" @click="handleCancel">取消</button>
          <button class="popup-btn confirm-btn" @click="handleSubmit">提交</button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import {
  getOrderList,
  cancelOrder,
  delOrder,
  confirmOrder,
  getwxReceiveDetail,
  getwechatSyncCheck,
} from "@/api/order";
import {compareWeChatVersion} from "@/utils/tools";

import {prepay} from "@/api/app";
import {loadingType} from "@/utils/type";

import {wxpay, alipay} from "@/utils/pay";
import {loadingFun} from "@/utils/tools";

export default {

  data() {
    return {
      page: 1,
      orderList: [],
      status: loadingType.LOADING,
      showCancel: false,
      type: 0,
      orderId: "",
      showLoading: false,
      pay_way: "",
      processedOrderList: [],
      showNegotiatePopup: false, // 添加协商取消弹窗控制
      currentOrderId: null,      // 当前操作的订单ID
      show: false, // 控制评论弹窗显示
      formData: {
        efficiency: 5,
        skill: 5,
        attitude: 5,
        content: ""
      }
    };
  },

  components: {},
  props: {
    orderType: {
      type: String,
    },
  },
  created: function () {
    uni.$on("refreshorder", () => {
      this.reflesh();
    });
    uni.$on("payment", (params) => {
      if (params.result) {
        this.reflesh();
        uni.navigateBack();
        setTimeout(() => this.$toast({title: "支付成功"}), 0.5 * 1000);
      }
    });
  },
  beforeMount: function () {
    this.getOrderListFun();
  },
  destroyed: function () {
    uni.$off(["payment", "refreshorder"]);
  },
  methods: {
    reflesh() {
      this.page = 1;
      this.orderList = [];
      this.status = loadingType.LOADING;
      this.type = 0;
      this.getOrderListFun();
    },

    reload() {
      this.status = loadingType.LOADING;
      this.getOrderListFun();
    },

    orderDialog() {
      this.$refs.orderDialog.open();
    },

    delOrder(id) {
      this.orderId = id;
      this.type = 1;
      this.$nextTick(() => {
        this.orderDialog();
      });
    },
    negotiateCancelOrder(id) {
      this.currentOrderId = id;
      this.showNegotiatePopup = true;
    },

    // 添加跳转客服页面方法
    goToCustomerService() {
      this.showNegotiatePopup = false;
      // 这里替换为实际的客服页面路径
      uni.navigateTo({
        url: '/pages/customer_service/customer_service' // 请根据实际路径修改
      });
    },
    // 小程序确认收货
    comfirmReceive(transaction_id) {
      return new Promise((resolve, reject) => {
        wx.openBusinessView({
          businessType: "weappOrderConfirm",
          extraData: {
            transaction_id,
          },
          success({extraData}) {
            if (extraData.status == "success") {
              resolve("确认收货");
            } else {
              resolve("取消收货");
            }
          },
          fail(err) {
            reject(err);
          },
        });
      });
    },
    //查询是否收货成功
    querycomfirmReceive(id) {
      return new Promise((resolve, reject) => {
        getwechatSyncCheck({id})
            .then(({data}) => {
              if (data.order.order_state === 4) {
                resolve("已确认收货");
              } else {
                reject("未确认收货");
              }
            })
            .catch((err) => {
              reject(err);
            });
      });
    },
    comfirmOrder(id, pay_way) {
      this.orderId = id;
      this.pay_way = pay_way;
      this.type = 2;
      this.$nextTick(async () => {
        // #ifdef MP-WEIXIN
        let res = {};
        if (this.pay_way === 1) {
          res = await getwechatSyncCheck({id: this.orderId});
          console.log(res);
        }
        if (
            compareWeChatVersion("2.6.0") === 1 &&
            wx.openBusinessView &&
            this.pay_way === 1 &&
            res.data.order.order_state !== 1
        ) {
          try {
            const {data} = await getwxReceiveDetail({
              order_id: this.orderId,
            });
            await this.comfirmReceive(data.transaction_id);
            await this.querycomfirmReceive(this.orderId);
            await confirmOrder(this.orderId);
          } catch (error) {
            console.log(error);
          }
          this.reflesh();
        } else {
          this.orderDialog();
        }
        // #endif

        // #ifndef MP-WEIXIN
        this.orderDialog();
        // #endif
      });
    },

    cancelOrder(id) {
      this.orderId = id;
      this.type = 0;
      this.$nextTick(() => {
        this.orderDialog();
      });
    },

    payNow(id) {
      // this.showLoading = true

      uni.navigateTo({
        url: `/pages/payment/payment?from=${"order"}&order_id=${id}`,
      });

      // prepay({
      // 	from: 'order',
      // 	order_id: id
      // }).then(res => {
      // 	let args = res.data;
      // 	this.showLoading = false
      // 	if (res.code == 1) {
      // 		wxpay(args).then((resPay) => {
      // 			if(resPay == 'success') {
      // 				this.$toast({
      // 					title: "支付成功"
      // 				})
      // 				uni.$emit("refreshorder")
      // 			}
      // 		})
      // 	}else if(res.code == 20001){
      // 		alipay(args).then((resPay) => {
      // 			if(resPay == 'success') {
      // 				this.$toast({
      // 					title: "支付成功"
      // 				})
      // 				uni.$emit("refreshorder")
      // 			}
      // 		})
      // 	}
      // });
    },

    goDetail(id) {
      uni.navigateTo({
        url: `/pages/order_details/order_details?id=${id}`,
      });
    },

    async getOrderListFun() {
      let {page, orderType, orderList, status} = this;
      const data = await loadingFun(getOrderList, page, orderList, status, {
        type: orderType,
      });
      if (!data) return;
      this.page = data.page;
      this.orderList = data.dataList.map(item => ({
        ...item,
        statusClass: this.getStatusClass(item.order_status),
        statusIcon: this.getStatusIcon(item.order_status)
      }));
      this.status = data.status;
    },
    goPage(url) {
      uni.navigateTo({
        url,
      });
    },
    goodCount(goodLists) {
      console.log(goodLists);
      let count = 0;
      goodLists.forEach((item) => {
        count += item.goods_num;
      });
      return count;
    },
    getStatusClass(status) {
      switch (status) {
        case 0: // 待支付
          return 'error';
        case 1: // 待确认
        case 3: // 待接单
        case 4: // 服务中
        case 5: // 待完结
          return 'muted';
        case 6: // 已完成
          return 'primary';
        default:
          return 'muted';
      }
    },

    getStatusIcon(status) {
      switch (status) {
        case 0: // 待支付
          return 'clock';
        case 1: // 待确认
          return 'checkmark-circle';
        case 3: // 待接单
          return 'checkmark-circle';
        case 4: // 服务中
          return 'clock';
        case 5: // 待完结
          return 'clock';
        case 6: // 已完成
          return 'checkmark-circle';
        default:
          return 'clock';
      }
    },
    /**
     * 跳转到评价页面
     * @param {Object} item - 订单项数据
     */
    goToComment(item) {
      // 设置当前要评价的订单ID
      this.commentOrderId = item.id;
      // 重置表单数据
      this.formData = {
        efficiency: 5,
        skill: 5,
        attitude: 5,
        content: ""
      };
      // 显示评价弹窗
      this.show = true;
    },

    /**
     * 处理评论取消
     */
    handleCancel() {
      this.show = false;
      this.commentOrderId = null;
    },

    /**
     * 处理评论提交
     */
    handleSubmit() {
      // 这里应该调用提交评论的API
      console.log('提交评论:', {
        orderId: this.commentOrderId,
        ...this.formData
      });

      // 模拟提交成功
      this.show = false;
      this.commentOrderId = null;
      this.$toast({title: "评价提交成功"});
      this.reflesh(); // 刷新订单列表
    },
    onClose() {
      this.show = false;
      this.commentOrderId = null;
    },
  },
  computed: {
    getOrderStatus() {
      return (status) => {
        let text = "";
        switch (status) {
          case 0:
            text = "待支付";
            break;
          case 1:
            text = "待发货";
            break;
          case 2:
            text = "待收货";
            break;
          case 3:
            text = "已完成";
            break;
          case 4:
            text = "订单已关闭";
            break;
        }
        return text;
      };
    },
    getCancelTime() {
      return (time) => time - Date.now() / 1000;
    },
  },
};
</script>
<style lang="scss">
.order-info {
  padding: 20rpx;
  color: #959faf;

  .info-row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10rpx;

    .value {
      text-align: right;
      flex: 1;
      margin-left: 20rpx;
    }
  }
}

.order-list {
  // min-height: calc(100vh - 80rpx);
  padding: 0 20rpx;
  overflow: hidden;

  .order-item {
    border-radius: 10rpx;

    .order-header {
      height: 80rpx;
      margin: 0 20rpx;
      border-bottom: 1px solid #f0f1f5;
    }

    .order-status {
      display: flex;
      align-items: center;
      gap: 5rpx; // 图标和文字之间的间距

      &.error {
        color: #FF2C3C; // 红色
      }

      &.muted {
        color: #999999; // 灰色
      }

      &.primary {
        color: #007AFF; // 蓝色
      }
    }

    .order-header .row {
      color: #030303;
      font-weight: bold;
    }

    .all-price {
      text-align: right;
      padding: 0 24rpx 20rpx;
    }

    .order-footer {
      margin: 0 20rpx;
      height: 100rpx;
      border-top: $-solid-border;

      .plain {
        border: 1px solid #2d6af4;
        color: #2d6af4;

        &.red {
          border-color: $-color-primary;
          color: $-color-white;
        }
      }
    }
  }
}

.negotiate-popup {
  background: linear-gradient(180deg, #d1dfff 0%, #ffffff 40%);
  padding: 40rpx;
  text-align: center;
  .icon-alert {
    width: 120rpx;
    height: 100rpx;
  }

  .popup-header {
    font-size: 38rpx;
    font-weight: bold;
    margin-bottom: 30rpx;
    color: #333333;
  }

  .popup-content {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 40rpx;
    line-height: 40rpx;
  }

  .popup-footer {
    justify-content: space-between;

    .popup-btn {
      flex: 1;
      height: 70rpx;
      line-height: 70rpx;
      border-radius: 35rpx;
      margin: 0 20rpx;
      font-size: 28rpx;

      &.cancel-btn {

        background-color: #f2f4f8;
        color: #a6b0c6;
      }

      &.confirm-btn {
        background-color: #0066ff;
        color: #fff;
        border: none;
      }
    }
  }
}

.comment-popup {
  padding: 40rpx;
  text-align: center;
  background: linear-gradient(180deg, #d1dfff 0%, #ffffff 40%);

  .icon-pl {
    width: 120rpx;
    height: 110rpx;
  }

  .popup-header {
    font-size: 38rpx;
    font-weight: bold;
    margin-bottom: 30rpx;
    color: #333333;
  }

  .comment-form {
    margin-bottom: 40rpx;

    .comment-item {
      margin-bottom: 30rpx;
      text-align: left;
      .comment-row {
        display: flex;
        align-items: center;
        margin-bottom: 0;
      }
      .comment-label {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 5rpx;
        flex-shrink: 0;
        margin-right: 20rpx; // 添加右边距
      }

      .comment-textarea {
        width: 100%;
        height: 150rpx;
        padding: 20rpx;
        border: 1rpx solid #eee;
        border-radius: 10rpx;
        font-size: 26rpx;
        box-sizing: border-box;
      }
    }
  }

  .popup-footer {
    justify-content: space-between;

    .popup-btn {
      flex: 1;
      height: 70rpx;
      line-height: 70rpx;
      border-radius: 35rpx;
      margin: 0 20rpx;
      font-size: 28rpx;

      &.cancel-btn {
        background-color: #f2f4f8;
        color: #a6b0c6;
      }

      &.confirm-btn {
        background-color: #0066ff;
        color: #fff;
        border: none;
      }
    }
  }
}

</style>
